シンプルな React Component を TDD で実装する
from Testing React with Testing Library
warning.icon 本来は都度テストを実行するが、ここでは省略している
<button> をラップするだけの単純なコンポーネントを TDD で実装する
Step 1: 定義
テストを書く
code:CarouselButton.test.tsx
describe("CarouselButton", () => {
it("renders a <button>", () => {
render(<CarouselButton />);
expect(screen.getByRole("button")).toBeInTheDocument();
});
});
テストをパスする最低限の実装を書く
code:CarouselButton.tsx
const CarouselButton = () => <button />
export default CarouselButton;
Step 2: 子要素を Props として受け取れるようにする
テストを書く
code:CarouselButton.test.tsx
it("passes children through to the <button>", () => {
const text = "Button text";
render(<CarouselButton>{text}</CarouselButton>);
expect(screen.getByRole("button")).toHaveTextContent(text);
});
テストをパスする最低限の実装を書く
code:CarouselButton.tsx
const CarouselButton = ({ children }: { children?: React.ReactNode }) => (
<button>{children}</button>
);
Step 3: <button> 要素がサポートするすべての Props を受け取れるようにする
テストを書く
code:CarouselButton.test.tsx
it("passes other props through to the <button>", () => {
const className = "my-carousel-button";
const dataAction = "prev";
render(
<CarouselButton className={className} data-action={dataAction}>
Button text
</CarouselButton>,
);
expect(screen.getByRole("button")).toHaveClass(className);
expect(screen.getByRole("button")).toHaveAttribute(
"data-action",
dataAction,
);
});
warning.icon React における Props は基本的に camelCase だが、data- や aria- は例外的に kebab-case で表す
https://react.dev/reference/react-dom/components/common#common-props
テストをパスする最低限の実装を書く
code:CarouselButton.tsx
import { ComponentPropsWithRef } from "react";
const CarouselButton = (props: ComponentPropsWithRef<"button">) => (
<button {...props} />
);
#React #TDD